package org.apache.servicecomb.fence.resource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.servicecomb.fence.api.resource.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentRepository {

    @Autowired
    private DataSource dataSource;


    public Student getStudentById(int id) {
        String sql = "SELECT AGE, NAME, CLASS_ID FROM student WHERE id = ?";
        Student student = null;

        try (Connection connection = dataSource.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setInt(1, id);
            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                student = new Student();
                student.setAge(resultSet.getInt("AGE"));
                student.setName(resultSet.getString("NAME"));
                student.setClassId(resultSet.getLong("CLASS_ID"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return student;
    }
}